<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
      <el-form-item label="仓库编号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入仓库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库类型" prop="typeNo" >
        <el-select v-model="queryParams.typeNo" clearable placeholder="请选择仓库类型"  >
          <el-option
            v-for="dict in dict.type.basic_storehouse_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:storehouse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:storehouse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:storehouse:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="editPlanView"
        >平面图</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['basic:storehouse:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:storehouse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storehouseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="仓库编号" align="center" prop="no" />
      <af-table-column label="仓库名称" align="center" prop="name" />
      <af-table-column label="仓库类型" align="center" prop="typeNo" >
      <template slot-scope="scope">
        <dict-tag :options="dict.type.basic_storehouse_type" :value="scope.row.typeNo"/>
      </template>
      </af-table-column>
      <el-table-column label="是否线边仓" align="center" prop="isLine"  width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isLine"/>
        </template>
      </el-table-column>
      <el-table-column label="是否虚拟仓" align="center" prop="isVirtual" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isVirtual"/>
        </template>
      </el-table-column>
      <af-table-column label="仓库功能权限" align="center" prop="permissionName" />
      <af-table-column label="所属工厂" align="center" prop="factoryNo" >
        <template slot-scope="scope">
          <dict-tag :options="factoryLabel" :value="scope.row.factoryNo"/>
        </template>
      </af-table-column>
      <el-table-column label="备注" align="center" prop="remark" min-width="152"/>
      <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="152"/>
      <el-table-column label="最后更新人" align="center" prop="updateBy" min-width="100"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="152"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12" >
            <el-form-item label="仓库编号" prop="no">
              <el-input v-model="form.no" placeholder="请输入仓库编号" :disabled="!!form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="仓库名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" >
            <el-form-item label="仓库类型" prop="typeNo">
              <el-select style="width:100%;" v-model="form.typeNo" filterable placeholder="请选择线边仓">
                <el-option
                  v-for="dict in dict.type.basic_storehouse_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="所属工厂" prop="factoryNo">
              <el-select style="width:100%;" v-model="form.factoryNo" filterable placeholder="请选择所属工厂">
                <el-option
                  v-for="dict in factoryOptionList"
                  :key="dict.no"
                  :label="dict.no + '-' + dict.abbreviation"
                  :value="dict.no"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" >
            <el-form-item label="是否是虚拟仓" prop="isVirtual">
              <el-select style="width:100%;" v-model="form.isVirtual" filterable placeholder="请选择油品名称">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="仓库权限" prop="permissionNo">
              <el-select style="width:100%;" v-model="form.permissionNo" filterable placeholder="请选择仓库权限">
                <el-option
                  v-for="dict in storehousePermissionList"
                  :key="dict.no"
                  :label="dict.name"
                  :value="dict.no"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" >
            <el-form-item label="是否线边仓" prop="isLine">
              <el-select style="width:100%;" v-model="form.isLine" filterable placeholder="请选择线边仓">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listStorehouse,listStorehousePermission, getStorehouse, delStorehouse, addStorehouse, updateStorehouse } from "@/api/basic/storehouse";
import { getToken } from "@/utils/auth";
import { listFactory } from "../factory/api/factory";

export default {
  name: "Storehouse",
  dicts: ['sys_yes_no', 'basic_storehouse_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库表格数据
      storehouseList: [],
      // 仓库权限列表数据
      storehousePermissionList: [],
      // 所选厂区下拉选
      factoryOptionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        name: null,
        typeNo: null,
        typeName: null,
        roleNo: null,
        isLine: null,
        isVirtual: null,
        factoryNo: null,
        status: null,
        outerNo: null,
        isCustom: null,
        isPicking: null,
        isShip: null,
        isOtherOut: null,
        isAllocation: null,
        isScrap: null,
        isInventory: null,
        isMove: null,
        isPack: null,
        sort: null,
        isVosOutbound: null,
        isVosReturn: null,
        isVosPicking: null,
        isVosRigout: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basic/storehouse/importExcel"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        no: [
          { required: true, message: "仓库编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" }
        ],
        typeNo: [
          { required: true, message: "仓库类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        permissionNo: [
          { required: true, message: "仓库权限不能为空", trigger: "blur" }
        ],
        factoryNo: [
          { required: true, message: "所属工厂不能为空", trigger: "blur" }
        ],
      },
      factoryLabel: null,
    };
  },
  created() {
    this.getList();
    this.getStorehousePermission();
    this.getFactoryList();
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true;
      listStorehouse(this.queryParams).then(response => {
        this.storehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**
     * 获取工厂列表
     **/
    getFactoryList(){
      listFactory().then(response => {
        const genderSet = new Set(response.rows.map(item => item.no));
        this.factoryLabel = Array.from(genderSet).map(no => {
          return {
            label: response.rows.find(item => item.no === no).abbreviation,
            value: no
          };
        });
        this.factoryOptionList = response.rows;
      });
    },
    /**
     * 查询仓库权限列表
     * */
    getStorehousePermission() {
      listStorehousePermission().then(response => {
        this.storehousePermissionList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        name: null,
        typeNo: null,
        typeName: null,
        roleNo: null,
        isLine: 'N',
        isVirtual: 'N',
        factoryNo: null,
        status: "0",
        outerNo: null,
        remark: null,
        isCustom: null,
        isPicking: null,
        isShip: null,
        isOtherOut: null,
        isAllocation: null,
        isScrap: null,
        isInventory: null,
        isMove: null,
        isPack: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        sort: null,
        isVosOutbound: null,
        isVosReturn: null,
        isVosPicking: null,
        isVosRigout: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.no)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仓库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStorehouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改仓库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 赋值form表单权限名称字段
          this.$set(this.form,'permissionName',this.storehousePermissionList.find(item => item.no === this.form.permissionNo).name)
          if (this.form.id != null) {
            updateStorehouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStorehouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.no || this.nos;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delStorehouse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 跳转编辑工厂平面图
    editPlanView(row){
      const nos = row.no || this.nos;
      // this.$router.push('/monitor/job-log/index/' + this.ids[0])
      this.$router.push('/basic/storehouse/plan-view/index/'+ nos)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/storehouse/export', {
        ...this.queryParams, ids: this.ids
      }, `仓库管理_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "仓库导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('basic/storehouse/importTemplate', {
      }, `仓库模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
